package byron.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import byron.client.*;

/**
 * The byron-braun server. It holds the data source sent from the client and responds to
 * incoming requests.
 *
 */
@SuppressWarnings("serial")
public class ByronServer extends RemoteServiceServlet implements ByronService {

	private DataSource source;
	
	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getContentType().startsWith("text/x-gwt-rpc")) {
			super.service(request, response);
		} else {
			// Create a factory for disk-based file items
			FileItemFactory factory = new DiskFileItemFactory();

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			// Parse the request
			System.out.println("\n--- Parsing request ---");
			try {
				// FileItems
				List items = upload.parseRequest(request);
				for (Object o : items) {
					final FileItem item = (FileItem)o; 
					System.out.println(item.getName());
				}
				
				// Create new datasource
				final FileItem file = (FileItem)items.get(0);
				if (file.getName().endsWith(".csv")) {
					source = new CsvSource(file.getString(), "Serie");
				} else {
					//throw new Exception("Unsupported data type!");
					System.err.println("Unsupported file type!");
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public List<CellData> getColumn(String attributeName, String key) {
		return source.getColumn(attributeName, key);
	}

	public List<String> getHeaders() {
		return source.getAttributes();
	}

	public List<List<CellData>> getRows(String key) {
		return source.getRows(key);
	}

}
